package org.project.d.network.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.project.d.network.protocol.Packet;
import org.project.d.network.protocol.UDPPacket;

import java.util.List;

/**
 * @author lin
 * @version V1.0
 * @description
 * @date 2020/6/11 4:42 下午
 */
@ChannelHandler.Sharable
public class UDPPacketEncoder extends MessageToMessageEncoder<UDPPacket> {

    @Override
    protected void encode(ChannelHandlerContext ctx, UDPPacket msg, List<Object> out) throws Exception {
        ByteBuf buf = ctx.alloc()
                .buffer(Packet.headLenth + msg.getBodyLength());
        Packet.encodePacket(msg, buf);
        DatagramPacket datagramPacket = new DatagramPacket(buf, msg.getAddress());
        out.add(datagramPacket);
    }
}
